<script setup lang="ts">
import { ref, reactive } from 'vue'
import { Form as AForm, Input as AInput, Button as AButton, message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import type { FormInstance } from 'ant-design-vue'
import { register, sendVerifyCode } from '@/api/user'
import type { RegisterData } from '@/api/user'
import type { AxiosResponse } from 'axios'

const formRef = ref<FormInstance | null>(null)
const router = useRouter()
const loading = ref(false)
const countdown = ref(0)

const formState = reactive<RegisterData>({
  userAccount: '',
  userPassword: '',
  checkPassword: '',
  email: '',
  cpacha: '',
})

interface Result<T> {
  code: number
  message: string
  data: T | null
}

interface UserRegisterVO {
  id: number
  userAccount: string
  email: string
}

// 密码强度验证
const validatePassword = async (_rule: unknown, value: string) => {
  if (!value) {
    return Promise.reject('请输入密码')
  }
  if (value.length < 6) {
    return Promise.reject('密码长度不能小于6位')
  }
  if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{6,20}$/.test(value)) {
    return Promise.reject('密码必须包含大小写字母和数字')
  }
  return Promise.resolve()
}

// 确认密码验证
const validateConfirmPassword = async (_rule: unknown, value: string) => {
  if (!value) {
    return Promise.reject('请确认密码')
  }
  if (value !== formState.userPassword) {
    return Promise.reject('两次输入的密码不一致')
  }
  return Promise.resolve()
}

const handleSendCode = async () => {
  try {
    if (!formRef.value) {
      throw new Error('Form reference is not initialized')
    }

    await formRef.value.validateFields(['email'])
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)

    try {
      await sendVerifyCode(formState.email)
      message.success('验证码已发送')
    } catch (error) {
      console.warn('发送验证码API出现错误，但验证码可能已发送:', error)
      // 不显示错误提示，因为验证码实际上已经发送
      message.info('验证码已发送，如未收到请稍后重试')
    }
  } catch (error) {
    console.error('发送验证码前验证失败:', error)
    message.error('请输入正确的邮箱格式')
  }
}

const handleSubmit = async () => {
  try {
    loading.value = true

    if (!formRef.value) {
      throw new Error('Form reference is not initialized')
    }

    await formRef.value.validate()

    const data: RegisterData = {
      userAccount: formState.userAccount.trim(),
      userPassword: formState.userPassword.trim(),
      checkPassword: formState.checkPassword.trim(),
      email: formState.email.trim(),
      cpacha: formState.cpacha.trim(), // 添加 trim() 方法
    }

    const res: AxiosResponse<Result<UserRegisterVO>> = await register(data)
    console.log(res)

    if (res.data.code === 200) {
      message.success('注册成功')
      router.push('/login')
    } else {
      message.error(res.data.message || '注册失败，请重试')
    }
  } catch (error) {
    console.error(error)
    message.error('注册失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="register-container">
    <div class="register-box">
      <h2>用户注册</h2>
      <a-form
        :model="formState"
        :rules="{
          userAccount: [
            { required: true, message: '请输入工号或学号', trigger: 'blur' },
            { min: 3, message: '工号或学号长度不能小于3位', trigger: 'blur' },
          ],
          userPassword: [{ validator: validatePassword, trigger: 'blur' }],
          checkPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }],
          email: [
            { required: true, message: '请输入邮箱号', trigger: 'blur' },
            {
              pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
              message: '请输入正确的邮箱号',
              trigger: 'blur',
            },
          ],
          verifyCode: [
            { required: true, message: '请输入验证码', trigger: 'blur' },
            { len: 6, message: '验证码长度为6位', trigger: 'blur' },
          ],
        }"
        ref="formRef"
        @finish="handleSubmit"
        layout="vertical"
      >
        <a-form-item name="userAccount" label="工号或学号">
          <a-input v-model:value="formState.userAccount" placeholder="请输入工号或学号" />
        </a-form-item>

        <a-form-item name="email" label="邮箱号">
          <a-input v-model:value="formState.email" placeholder="请输入邮箱号" />
        </a-form-item>

        <a-form-item name="capcha" label="验证码">
          <div class="verify-code-wrapper">
            <a-input v-model:value="formState.cpacha" placeholder="请输入验证码" />
            <a-button :disabled="countdown > 0" @click="handleSendCode" class="send-code-btn">
              {{ countdown > 0 ? `${countdown}s后重新发送` : '发送验证码' }}
            </a-button>
          </div>
        </a-form-item>

        <a-form-item name="userPassword" label="密码">
          <a-input-password v-model:value="formState.userPassword" placeholder="请输入密码" />
        </a-form-item>

        <a-form-item name="checkPassword" label="确认密码">
          <a-input-password v-model:value="formState.checkPassword" placeholder="请确认密码" />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" :loading="loading" block>注册</a-button>
        </a-form-item>

        <div class="login-link">
          已有账号？
          <router-link to="/login">立即登录</router-link>
        </div>
      </a-form>
    </div>
  </div>
</template>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
}

.register-box {
  width: 100%;
  max-width: 400px;
  padding: 2rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

h2 {
  text-align: center;
  margin-bottom: 2rem;
  color: #1890ff;
}

.verify-code-wrapper {
  display: flex;
  gap: 8px;
}

.send-code-btn {
  flex-shrink: 0;
  width: 120px;
}

.login-link {
  text-align: center;
  margin-top: 1rem;
}
</style>
